import React, { useState } from 'react'
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import { Upload, message, Image } from 'antd';
import { baseURL } from '../../aixos'

export default function UploadImage(props) {
  console.log('imageUrl', props.imageUrl)
  console.log('props', props)
  const { preview = false } = props
  const [loading, setLoading] = useState(false)
  // const [imageBase64, setImageBase64] = useState(null)

  const upLoadChange = info => {
    // console.log(info)
    if (info.file.status === 'uploading') {
      setLoading(true)
      return;
    }
    if (info.file.status === 'done') {
      // Get this url from response in real world.
      getBase64(info.file.originFileObj, imageUrl => {
        // 设置当前组件图片显示的路径
        // setImageBase64(imageUrl)
        // 设置需要传到后台的图片途径
        props.setImageUrl(info.file.response.path)
        setLoading(false)
      }
      );
    }
  };
  const beforeUpload = (file) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('You can only upload JPG/PNG file!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('Image must smaller than 2MB!');
    }
    return isJpgOrPng && isLt2M;
  }
  function getBase64(img, callback) {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
  }
  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>Upload</div>
    </div>
  );

  const stopPropagation = (e) => {
    // e.stopPropagation()
    console.log('stopPropagation')
  }

  return (
    <Upload
      name="avatar"
      listType="picture-card"
      className="avatar-uploader"
      showUploadList={false}
      action={`${baseURL}/profile`}
      beforeUpload={beforeUpload}
      onChange={upLoadChange}
    >
      {props.imageUrl ? <Image src={props.imageUrl} preview={preview} width="100%" height="100%" alt="avatar"
        onClick={stopPropagation}
      /> : uploadButton}
    </Upload>
  )
}
